<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\wendasns\controller;
use app\wendasns\WenBaseController;

use app\wendasns\model\Question as byQuestion;
use app\wendasns\model\Category;
use app\wendasns\model\Answer;
use app\wendasns\model\Report;
use app\wendasns\model\Seo;
use app\wendasns\model\User;
use app\wendasns\service\PwSeo;
use app\wendasns\service\PwAsk;
use app\wendasns\model\Collect;
use app\wendasns\service\PwSrv;
	
use wendasns\Wend;
use think\Exception;
use think\App;
use think\facade\Route;
use think\facade\View;

class Question extends WenBaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    	if(in_array(request()->action(true), ['post','adopt','edit','remove','close','collect'])){
    		if(!$this->loginUser->isLogin) error('请登录后再操作',[],['refresh'=>0]);
    	}
    }
    
	//问题列表页
    public function index($cname='all', $type='new', $page=1)
    {
    	
		$category = Category::where('type', 'question')->select();
		$categoryname = '';
		foreach($category as $v){
			if($v->dir_name==$cname){
				$categoryname = ' - '.$v->name;
			}
		}
		
		$typear = ['new'=>'最新','hot'=>'热门','unsolved'=>'未解决','unanswer'=>'未回答','solved'=>'已解决'];
		$pages = $page>1?' - 第'.$page.'页':'';
		$logs = PwAsk::getAll($type, $cname, $page);
		
		$data = [
			'category' => $category,
			'logs' => $logs,
			'type' => $type,
			'categoryname' => $cname
		];
		
		$dm = Seo::where('type','question')->find();
		$seo = new PwSeo();
		$seo->title = sprintf('%s%s%s%s',$typear[$type],$dm->title,$categoryname,$pages);
		$seo->description = $dm->description;
		$seo->keywords = $dm->keywords;
		$seo->set();
		View::assign($data);
		event('QuestionListPage');
        return View::fetch();
    }

    //问题详情页
	public function show($id=0, $kid='', $category='')
	{
		
		if($kid){
			$dm = byQuestion::getByKid($kid);
		}else{
			$dm = byQuestion::find($id);
		}
		
		if(!$dm || $dm->remove){
			error('问题不存在或已经失效');
		}

		if($dm->status=='check'){
			if($dm->user_id!==$this->loginUser->uid){
				if(!admin_check('thread.check')){
					error('问题审核中',[],['refresh'=>0]);
				}
			}
		}

		if(!empty($category) && $dm->categorys->dir_name!==$category){
			error('问题不存在或已经失效');
		}
		
		//分页大小
		$limit = configure('page.pageAnswer', 10);
		
		//返回标签数组
		/*$dm->withAttr('tags',function($value, $data) {
        	return explode(',', $value);
        });*/
        
		//刷新访问量
		$dm->inc('visits')->update();
        
        
		//最佳答案
		$dm->adopt = $dm->answers()->find($dm->adopt_id);

		//回答列表
		$answer = $dm->answers()->where([
			['id','<>',$dm->adopt_id],
			['status','=','normal'],
			['remove','=',0]
		])->order('create_time', 'desc')->paginate(2);
        
        //相关问题
        $alike = byQuestion::where('tags','like',array_map(function($value){return "%$value%";},explode(',',$dm->tags)),'OR')->where('id','<>',$dm->id)->order('create_time','desc')->limit(10)->select();
        
        //收藏
        $dm->iscollect = Collect::where('mold','question')->where('user_id',$this->loginUser->uid)->where('source_id',$dm->id)->find();
        
        
		$data = [
			'question' => $dm,
			'answer' => $answer,
			'alike' => $alike,//关联问题
		];
		$seo = new PwSeo();
		$seo->title = $dm->title;
		$seo->description = substr_format(strip_tags($dm->content),80);
		$seo->keywords = $dm->tags;
		$seo->set();
		View::assign($data);
		event('QuestionPage');
		return View::fetch();
	}
	
	//提问页面
    public function post()
    {
    	action_check('question.post');
    	if(request()->isPost()){
    		$this->ask();
    	}
    	$category = Category::where('type','question')->where('status',1)->select();
		$seo = new PwSeo();
		$seo->title = '提问';
		$seo->set();
    	return view('post',['category'=>$category]);
    }

    //问题关闭，禁止回答
    public function close()
    {
    	$qid = input('post.qid',0,'intval');
        try {
        	$question = new PwAsk();
            $question->id = $qid;
            $question->close();
        } catch (Exception $e) {
            error($e->getMessage());
        }
    	success('操作成功');
    }
    
    //采纳
    public function adopt()
    {
    	$qid = input('post.id',0,'intval');
    	$aid = input('post.aid',0,'intval');
    	$content = input('post.content','','wendasns\facade\Filter::cleanHtml');//采纳评语
    	action_check('question.adopt');
        try {
        	$question = new PwAsk();
        	$question->id = $qid;
        	$question->aid = $aid;
            $question->content = $content;
            $question->adopt();
        } catch (Exception $e) {
            error($e->getMessage());
        }
    	success('操作成功');
    }

    //修改问题
    public function edit()
    {
    	$qid = input('post.id',0,'intval');
    	$content = input('post.content','','');
    	action_check('question.edit');
        try {
        	$question = new PwAsk();
        	$question->id = $qid;
            $question->content = $content;
            $question->update();
        } catch (\think\Exception $e) {
            error($e->getMessage());
        }
        success('操作成功');
    }
    
    //删除
    public function remove()
    {
    	$qid = input('post.id',0,'intval');
    	action_check('question.remove');
        try {
        	$question = new PwAsk();
        	$question->id = $qid;
            $question->remove();
        } catch (Exception $e) {
            error($e->getMessage());
        }
    	success('操作成功');
    }
    
    //收藏
    public function collect()
    {
    	$id = input('post.id',0,'intval');
    	$dm = byQuestion::find($id);
    	if(!$dm){
    		error('问题不存在');
    	}
    	$collect = Collect::where('user_id',$this->loginUser->uid)->where('mold','question')->where('source_id',$id)->find();
    	if($collect){
    		error('已收藏');
    	}
    	Collect::create(['user_id'=>$this->loginUser->uid, 'mold'=>'question', 'source_id'=>$id, 'create_time'=>Wend::getTime()]);
    	$dm->inc('collect')->update();
    	$user = User::find($this->loginUser->uid);
    	$user->datas()->inc('collect')->update();
    	success('收藏成功');
    }
    
    //回答列表
    public function answer()
    {
    	$id = input('get.id',0,'intval');
    	$dm = byQuestion::find($id);
    	$answer = $dm->answers()->where([
			['id','<>',$dm->adopt_id],
			['status','=','normal'],
			['remove','=',0]
		])->order('create_time', 'desc')->paginate(1);
		
		return view('/answer',['question'=>$dm,'answer'=>$answer]);
    }
    
    //提问
    private function ask()
    {
    	$title = input('post.title','','wendasns\facade\Filter::cleanHtml');//标题,org\Filter::cleanHtml
    	$content = input('post.content','','');//问题描述
    	$anonymous = input('post.anonymous',0,'intval');//匿名提问
    	$category_id = input('post.category',0,'intval');//分类
    	$tags = input('post.tags','');//标签
    	$images = input('post.images',[]);//图片
    	$vcode = input('post.vcode','');//验证码

        //验证数据，包括敏感词
        try {
            $this->validate([
                'title'  => $title,
                'tags' => $tags,
                'content' => $content,
                'category' => $category_id,
                'vcode' => $vcode,
                'images' => $images
            ],'\app\wendasns\validate\Question');
        } catch (\think\exception\ValidateException $e) {
            error($e->getError());
        }

        try {
        	$question = new PwAsk();
            $question->uid = $this->loginUser->uid;
            $question->cid = $category_id;
            $question->title = $title;
            $question->content = $content;
            $question->tags = $tags;
            $question->anonymous = $anonymous;
            $question->images = $images;
            $dm = $question->save();
        } catch (Exception $e) {
            error($e->getMessage());
        }
    	
    	success('操作成功', [], ['referer'=>(string)url('wendasns/question/show',$dm)]);
    }

}